// components/audio-item/audio-item.js
var audio = wx.createInnerAudioContext()
const app = getApp()

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    audioList: Array,//文物语音列表
    location: String,//地点
  },

  /**
   * 组件的初始数据
   */
  data: {
    imgUrl: app.globalData.imgUrl,
    isPlaying: false,//播放按钮开关
    currentIndex: 0,//目前在播放的audio
    prevIndex: 0,//上次播放实例
    innerAudioContext: '',//音频实例
    duration: '',
    width: 'width:314rpx',//audio模块的宽度
    flexFlow: 'flex-flow:row nowrap',//audio中模块是否换行
    imgWidth: 'width:272rpx',
    marginLeft: 'margin-left:20rpx;width:54%',
    parent: '',//父组件
    startIndex: 0,//开始展示索引
    endIndex: 20000,//结束展示索引
    id: '',//文物id,
    process: 0,//音频进度
    waitFlag: false,
    canPlay:false,//音频是否可以播放
  },
  /**
 * 组件的生命周期
 */
  lifetimes: {
    ready: function () {
      // console.log(this.data.count)
      getCurrentPages().pop().setData({
        audioItemData: this.data
      })
      let length = getCurrentPages().length
      let path = getCurrentPages()[length - 1].route
      console.log(path)
      switch (path) {
        case "pages/exhibition/detail/detail":
          this.setData({
            parent: "detail",
            width: 'width:314rpx',
            endIndex: 2,
            imgWidth: 'width:314rpx',
            flexFlow: 'flex-flow:row wrap',//audio中是否换行
            marginLeft: ''
          })
          break;
        case "pages/exhibition/exhibition":
          this.setData({
            parent: "exhibition",
            width: 'width:100%',
          })
          break;
        case "pages/mime/myAudioTours/myAudioTours":
          this.setData({
            parent: "myAudioTours",
            width: 'width:100%',
          })
          break;
        case "pages/result/result":
          this.setData({
            parent: "result",
            width: 'width:100%',
          })
          break;
        case "pages/mime/history/history":
          this.setData({
            parent: "history",
            width: 'width:100%',
          })
          break;
        default:
          break;
      }
      console.log('语音组件安装')
      audio = wx.createInnerAudioContext()
      console.log(audio)
    },
    detached: function () {
      console.log('组件卸载')
      audio.stop()
    }
  },
  pageLifetimes: {
    // 组件所在页面的生命周期函数
    show: function () {
      audio = wx.createInnerAudioContext()
      console.log(audio)
    },
    hide: function () {
      console.log('页面隐藏')
    },
    resize: function () {
      console.log('页面尺寸变化')
    },
  },
  /**
   * 组件的方法列表
   */
  methods: {
    getAudioDetail: function (e) {
      var id = e.currentTarget.dataset.id;
      var location = e.currentTarget.dataset.location || this.data.location;
      // wx.navigateTo({
      //   url: "../../pages/exhibition/detail/detail?id=" + id + "&location=" + location
      // })
      switch (this.data.parent) {
        case "detail":
          wx.navigateTo({
            url: "/pages/exhibition/detail/detail?id=" + id + "&location=" + location+ '&museumCode=' + app.globalData.museumCode
          })
          break;
        case "exhibition":
          wx.navigateTo({
            url: "../../pages/exhibition/detail/detail?id=" + id + "&location=" + location+ '&museumCode=' + app.globalData.museumCode
          })
          break;
        case "myAudioTours":
          wx.navigateTo({
            url: "/pages/exhibition/detail/detail?id=" + id + "&location=" + location+ '&museumCode=' + app.globalData.museumCode
          })
          break;
        case "result":
          wx.navigateTo({
            url: "../../pages/exhibition/detail/detail?id=" + id + "&location=" + location+ '&museumCode=' + app.globalData.museumCode
          })
          break;
        case "history":
          wx.navigateTo({
            url: "/pages/exhibition/detail/detail?id=" + id + "&location=" + location+ '&museumCode=' + app.globalData.museumCode
          })
          break;

        default:
          break;
      }
      this.setData({ isPlaying: false })
      audio.destroy()
    },
    playAudio: function (e) {
      // this.recordProcess()
      console.log('开始播放按钮')
      let index = e.currentTarget.dataset.index;
      index === this.data.prevIndex ? console.log('继续播放') : this.setData({
        process: 0
      })
      console.log(this.data.process)
      console.log(index)
      let audioSrc = this.data.imgUrl + encodeURIComponent(this.data.audioList[index].audioPath)
      audio.src = audioSrc
      console.log(audioSrc)
      setTimeout(() => {        
        console.log(audio)
        console.log(audio.src)
        this.audioObserver()
        audio.play()
        this.setData({
          currentIndex: index,
          prevIndex: index,
          isPlaying: true,
        })
      }, 500);
    },
    stopAudio: function (e) {
      console.log('暂停播放按钮')
      let index = e.currentTarget.dataset.index;
      // audio.src = this.data.imgUrl + this.data.audioList[index].audioPath
      audio.pause()
      this.setData({
        currentIndex: index,
        isPlaying: false
      })
    },
    // audioObserver() {
    //   console.log('开始监听')
    //   console.log(this.data.canPlay,this.canPlay)
    //   // 音频由于网络等原因等待中的回调
    //   audio.onWaiting(() => {
    //     console.log('加载中')
    //     if(!this.data.canPlay){
    //       audio.pause() // 等待网络的时候音频暂停
    //       console.log('手动暂停一下')
    //       this.setData({
    //         waitFlag: true // 标明是onWaiting触发的暂停
    //       })
    //     }
    //   })
    //   // 音频准备就绪的回调
    //   audio.onCanplay(() => {
    //     setTimeout(() => {          
    //       console.log('可播放')
    //       console.log('缓冲时间', audio.buffered)
    //       // if (this.data.waitFlag) { // 如果是onWaiting触发的暂停，就立即播放

    //       // }
    //       audio.play() // play()方法看上去能重新触发onTimeUpdate()回调
    //       this.setData({
    //         waitFlag: false // 取消相应的flag标志位
    //       })
    //     }, 1000);
    //   })
    //   // 监听音频播放事件
    //   audio.onPlay(() => {
    //     console.log('正在播放', audio.duration)
    //     this.setData({
    //       canPlay:true
    //     })
    //   })
    //   // 监听音频暂停事件
    //   audio.onPause(() => {
    //     console.log('已经暂停播放')
    //   })
    //   // 监听音频播放进度更新事件
    //   audio.onTimeUpdate(() => {
    //     console.log(audio.currentTime)
    //     console.log(this.toSec(this.data.audioList[this.data.currentIndex].duration))
    //     this.setData({
    //       process: Math.floor(audio.currentTime)
    //     })
    //   })
    //   // 监听音频停止事件
    //   audio.onStop(() => {
    //     console.log('停止播放')
    //   })
    //   // 监听音频自然播放结束事件
    //   audio.onEnded(() => {
    //     console.log('自然播放结束')
    //     setTimeout(() => {
    //       this.setData({
    //         isPlaying: false,
    //         ctTime: 0,
    //         nowTime: "00:00",
    //       })
    //     }, 1000);
    //   })
    //   audio.onError((res) => {
    //     console.log(res.errMsg)
    //     console.log(res.errCode)
    //   })
    // },
    audioObserver() {
      console.log(audio)
      // 监听音频播放事件
      audio.onPlay(() => {
        console.log('正在播放', audio.duration)
      })
      // 监听音频暂停事件
      audio.onPause(() => {
        console.log('已经暂停播放')
        this.setData({
          isPlaying: false
        })
      })
      // 监听音频播放进度更新事件
      audio.onTimeUpdate(() => {
        console.log(audio.currentTime)
        this.setData({
          process: Math.floor(audio.currentTime)
        })
      })
      // 监听音频停止事件
      audio.onStop(() => {
        console.log('停止播放')
      })
      // 监听音频自然播放结束事件
      audio.onEnded(() => {
        console.log('自然播放结束')
        setTimeout(() => {
          this.setData({
            isPlaying: false,
            ctTime: 0,
            nowTime: "00:00",
          })
        }, 1000);
      })
    },
    // 记录语音播放记录
    recordProcess() {
      this.data.audioList.forEach(item => {
        item.durationSec = this.toSec(item.duration)
      })
      console.log(this.data.audioList)
    },
    // 时长转换为秒
    toSec(time) {
      var s = '';
      // console.log(time)
      // console.log(time.split(':').length)
      var length = time.split(':').length
      let hour, min, sec
      length > 3 ? hour = Number(time.split(':')[length - 3]) : hour = 0
      min = Number(time.split(':')[length - 2])
      sec = Number(time.split(':')[length - 1])
      // console.log(hour, min, sec)
      s = Number(hour * 3600) + Number(min * 60) + Number(sec);

      return s;
    },
  }
})
